package com.doublefish.doublefishrobot.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.ui.video.utils.VideoManager;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.LocalizationUtils;
import com.doublefish.doublefishrobot.utils.ToastUtil;
import com.doublefish.doublefishrobot.utils.ble.DFBleManager;
import com.doublefish.doublefishrobot.utils.socket.SocketManager;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by peak on 2024/10/15
 */
public abstract class BaseActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private Unbinder unbinder;

    private static final int CONNECT_SDK_PERMS = 0x200001;
    private static final int STORAGE_PERMS = 0x200002;
    private static final int BLE_PERMS = 0x200003;
    private static final int WIFI_PERMS = 0x200004;

    private String[] mRequestPermissions = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getLayoutId());
        getWindow().getDecorView().setBackground(getDrawable(R.drawable.bg_activity_gradient));

        // 设置状态栏颜色
//        getWindow().setStatusBarColor(Color.TRANSPARENT);
        setStatusBarView();

        unbinder = ButterKnife.bind(this);

        initView();
        initListener();
        initData();

//        permsAction();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        LocalizationUtils.getInstance().showLanguage(newBase);
        super.attachBaseContext(newBase);
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initListener();

    protected abstract void initData();

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
    }

//    private void permsAction() {
//        //申请权限
//        requestPerms();
//
//        //检查存储权限，如果有权限，就初始化数据库等
//        checkStoragePermission();
//        //检查WIFI的权限
//        checkWIFIPermission();
//        //检查蓝牙的权限
//        checkBlePermission();
//    }

    /**
     * 开始请求权限,请求所有权限, 华为不允许直接请求所有权限
     */
    private void requestPerms() {
        //申请权限
        List<String> allReqPermissions = new ArrayList<>();
        allReqPermissions.add(Manifest.permission.READ_PHONE_STATE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//            allReqPermissions.add(Manifest.permission.READ_MEDIA_AUDIO);
//            allReqPermissions.add(Manifest.permission.READ_MEDIA_IMAGES);
            allReqPermissions.add(Manifest.permission.READ_MEDIA_VIDEO);
        } else {
            allReqPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            allReqPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        allReqPermissions.add(Manifest.permission.BLUETOOTH);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            allReqPermissions.add(Manifest.permission.BLUETOOTH_SCAN);
            allReqPermissions.add( Manifest.permission.BLUETOOTH_CONNECT);
        }

        allReqPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        allReqPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            allReqPermissions.add(Manifest.permission.NEARBY_WIFI_DEVICES);
        }

        allReqPermissions.add(Manifest.permission.ACCESS_WIFI_STATE);
        allReqPermissions.add(Manifest.permission.CHANGE_WIFI_STATE);
        allReqPermissions.add(Manifest.permission.CHANGE_NETWORK_STATE);

        String[] permissions = new String[allReqPermissions.size()];
        allReqPermissions.toArray(permissions);

        mRequestPermissions = permissions;
        if (EasyPermissions.hasPermissions(this, mRequestPermissions)) {
            // Have permission, do the thing!
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.perm_toast_need_perms),
                    CONNECT_SDK_PERMS,
                    mRequestPermissions);
        }
    }

    /**
     * 请求存储权限 和 WIFI 权限
     */
    private void requestStoragePerms() {
        //申请权限
        List<String> allReqPermissions = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            allReqPermissions.add(Manifest.permission.READ_MEDIA_VIDEO);
        } else {
            allReqPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            allReqPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        allReqPermissions.add(Manifest.permission.ACCESS_WIFI_STATE);
        allReqPermissions.add(Manifest.permission.CHANGE_WIFI_STATE);
        allReqPermissions.add(Manifest.permission.CHANGE_NETWORK_STATE);

        String[] permissions = new String[allReqPermissions.size()];
        allReqPermissions.toArray(permissions);

        mRequestPermissions = permissions;
        if (EasyPermissions.hasPermissions(this, mRequestPermissions)) {
            // Have permission, do the thing!
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.perm_toast_need_perms),
                    STORAGE_PERMS,
                    mRequestPermissions);
        }
    }

    /**
     * 请求蓝牙权限 和 location 权限
     */
    private void requestBluetoothPerms() {
        //申请权限
        List<String> allReqPermissions = new ArrayList<>();

        allReqPermissions.add(Manifest.permission.BLUETOOTH);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            allReqPermissions.add(Manifest.permission.BLUETOOTH_SCAN);
            allReqPermissions.add( Manifest.permission.BLUETOOTH_CONNECT);
        }

        allReqPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        allReqPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);

        String[] permissions = new String[allReqPermissions.size()];
        allReqPermissions.toArray(permissions);

        mRequestPermissions = permissions;
        if (EasyPermissions.hasPermissions(this, mRequestPermissions)) {
            // Have permission, do the thing!
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.perm_toast_need_perms),
                    BLE_PERMS,
                    mRequestPermissions);
        }
    }

    /**
     * 请求wifi权限 和 location 权限
     */
    private void requestWifiPerms() {
        //申请权限
        List<String> allReqPermissions = new ArrayList<>();

        allReqPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        allReqPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            allReqPermissions.add(Manifest.permission.NEARBY_WIFI_DEVICES);
        }

        allReqPermissions.add(Manifest.permission.ACCESS_WIFI_STATE);
        allReqPermissions.add(Manifest.permission.CHANGE_WIFI_STATE);
        allReqPermissions.add(Manifest.permission.CHANGE_NETWORK_STATE);

        String[] permissions = new String[allReqPermissions.size()];
        allReqPermissions.toArray(permissions);

        mRequestPermissions = permissions;
        if (EasyPermissions.hasPermissions(this, mRequestPermissions)) {
            // Have permission, do the thing!
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.perm_toast_need_perms),
                    WIFI_PERMS,
                    mRequestPermissions);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode != CONNECT_SDK_PERMS) {
            return;
        }

        for (String perm : perms) {
            if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(perm) || Manifest.permission.READ_EXTERNAL_STORAGE.equals(perm)) {
                showToast(getResources().getString(R.string.perm_toast_need_store));
            } else if (Manifest.permission.READ_PHONE_STATE.equals(perm)) {
                showToast(getResources().getString(R.string.perm_toast_need_phoneinfo));
            } else if (Manifest.permission.ACCESS_FINE_LOCATION.equals(perm)) {
                showToast(getResources().getString(R.string.perm_toast_need_location));
            } else if (Manifest.permission.PACKAGE_USAGE_STATS.equals(perm)) {
                showToast(getResources().getString(R.string.perm_toast_need_usage_stats));
            } else if (Manifest.permission.BLUETOOTH.equals(perm)) {
                showToast(getResources().getString(R.string.perm_toast_need_bluetooth));
            }
        }

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.

        // FIXME: 2025/4/27 不要弹窗提示了，这个适配有问题
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            new AppSettingsDialog.Builder(this).build().show();
//        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == CONNECT_SDK_PERMS || requestCode == STORAGE_PERMS) {
            checkStoragePermission();
        }
    }

    //检查存储权限，如果有权限，就初始化数据库等
    public void checkStoragePermission() {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            String[] storagePermissions = {
                    Manifest.permission.READ_MEDIA_VIDEO
            };
            permissions = storagePermissions;
        } else {
            String[] storagePermissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            };
            permissions = storagePermissions;
        }
        if(EasyPermissions.hasPermissions(getApplicationContext(), permissions)) {
            //已经同意存储权限
            onStoragePermission();
        } else {
            requestStoragePerms();
        }
    }
    //同意了'存储'权限
    public void onStoragePermission() {
        AppCacheUtil.getInstance().setStoragePermissionEnable(true);
        //初始化视频管理工具
//        VideoManager.getInstance().init(getApplicationContext(), null);
        VideoManager.getInstance().init(AppCacheUtil.getInstance().getAppContext(), null);
    }

    //检查WIFI的权限
    public boolean checkWIFIPermission() {
        List<String> wifiPermissions = new ArrayList<>();

        wifiPermissions.add(Manifest.permission.ACCESS_WIFI_STATE);
        wifiPermissions.add(Manifest.permission.CHANGE_WIFI_STATE);
        wifiPermissions.add(Manifest.permission.CHANGE_NETWORK_STATE);

        wifiPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        wifiPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            wifiPermissions.add(Manifest.permission.NEARBY_WIFI_DEVICES);
        }

        String[] permissions = new String[wifiPermissions.size()];
        wifiPermissions.toArray(permissions);
        boolean granted = EasyPermissions.hasPermissions(getApplicationContext(), permissions);
        if (granted) {
            //初始化SocketManager
            SocketManager.getInstance().init(AppCacheUtil.getInstance().getAppContext());
        } else {
            requestWifiPerms();
        }
        return granted;
    }
    //检查蓝牙的权限
    public boolean checkBlePermission() {
        List<String> blePermissions = new ArrayList<>();

        blePermissions.add(Manifest.permission.BLUETOOTH);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            blePermissions.add(Manifest.permission.BLUETOOTH_SCAN);
            blePermissions.add( Manifest.permission.BLUETOOTH_CONNECT);
        }

        blePermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        blePermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);

        String[] permissions = new String[blePermissions.size()];
        blePermissions.toArray(permissions);

        boolean granted =  EasyPermissions.hasPermissions(getApplicationContext(), permissions);
        if (granted) {
            //初始化蓝牙管理工具
//            DFBleManager.getInstance().init(getApplication());
            DFBleManager.getInstance().init(getApplication(), AppCacheUtil.getInstance().getAppContext());
        } else {
            requestBluetoothPerms();
        }
        return granted;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // Do something after user returned from app settings screen, like showing a Toast.
            if (mRequestPermissions != null && !EasyPermissions.hasPermissions(this, mRequestPermissions)) {
                showToast(getResources().getString(R.string.perm_toast_not_allowed));
            }
        }
    }

    //从本地Assets中读取文件 设备分类
    public String readTypeFromFile(String fileName) {
        try {
            InputStream inputStream = getResources().getAssets().open(fileName);
            int length = inputStream.available();
            byte[] buff = new byte[length];
            inputStream.read(buff);
            inputStream.close();

            String json = new String(buff, StandardCharsets.UTF_8);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void showToast(String msg) {
        ToastUtil.showToast(this, msg);
    }

    //region    mark:检差多次快速点击造成初始化多个activity
    private String activityJumpTag = null;
    private long activityJumpTime = 0;

    @SuppressLint("RestrictedApi")
    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        if (canStartActivity(intent)) {
            super.startActivityForResult(intent, requestCode);
        }
    }

    //是否可以跳转
    private boolean canStartActivity(Intent intent) {
        String tag;
        if (intent.getComponent() != null) {
            //显示跳转
            tag = intent.getComponent().getClassName();
        } else if (intent.getAction() != null) {
            //隐式跳转
            tag = intent.getAction();
        } else {
            return true;
        }
        if (activityJumpTag == null || activityJumpTime == 0) {
            activityJumpTime = SystemClock.uptimeMillis();
            activityJumpTag = tag;
            return true;
        }
        //1000ms内不允许多次跳转
        if (tag.equals(activityJumpTag) && activityJumpTime + 1000 > SystemClock.uptimeMillis()) {
            return false;
        }
        activityJumpTime = SystemClock.uptimeMillis();
        activityJumpTag = tag;

        Log.i("activityJumpTime", "" + activityJumpTime);

        return true;
    }
    //endregion


    private View statusBarView;

    private void setStatusBarView() {
        //延时加载数据，保证Statusbar绘制完成后再findview。
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                initStatusBar();
                //不加监听,也能实现改变statusbar颜色的效果。但是会出现问题：比如弹软键盘后,弹popwindow后,引起window状态改变时,statusbar的颜色就会复原.
                getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        initStatusBar();
                    }
                });
                //只走一次
                return false;
            }
        });
    }

    /**
     * 颜色渐变
     */
    private void initStatusBar() {
        if (statusBarView == null) {
            //利用反射机制修改状态栏背景
            int identifier = getResources().getIdentifier("statusBarBackground", "id", "android");
            statusBarView = getWindow().findViewById(identifier);
        }
        if (statusBarView != null) {
            // 创建GradientDrawable对象
            GradientDrawable gradientDrawable = new GradientDrawable();
            // 设置渐变方向
            gradientDrawable.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT);
            // 设置渐变颜色数组
            gradientDrawable.setColors(new int[]{getColor(R.color.color_e477ab), getColor(R.color.color_eb6822)});
            // 设置视图的背景为GradientDrawable
            statusBarView.setBackground(gradientDrawable);

//            statusBarView.setBackgroundResource(R.drawable.bg_status_bar_gradient);
        } else {
// Log.w( "base","statusBarView is null.");
        }
    }
}